from turbogears import widgets, config
from turbogears import mochikit
from turbojson import jsonify
import turbogears.validators
from turbogears.config import get
from model import *
import validators
from turbogears import expose

GOOGLE_MAPS_URL='http://maps.google.com/maps?file=api&v=%s&key=%s'

class GoogleMapError(Exception): pass

class AbsLink(widgets.JSLink):

    def update_params(self, d):
        super(AbsLink, self).update_params(d)
        d["link"] = "%s" % self.mod

class GoogleMapWidget(widgets.Widget):
    """Google Map Widget"""

    vml_css  = 'v\:* {behavior:url(#default#VML);}' # CSS for IE VML
    onunload = 'GUnload()' # Cleans up after Google Maps
    xmlns    = 'xmlns:v="urn:schemas-microsoft-com:vml"' # XML Namespace (for IE VML).
    center_lat=0.0
    center_lng=0.0
    zoom=1
    dom_id='map'
    load_func='gmap_load'
    template='tgsampleapp.templates.googlemap'
    params = ["kml_url", "readonly"]

    def __init__(self, *kv, **kw):
        super(GoogleMapWidget, self).__init__(*kv, **kw)

        try:
            self._key = config.get('GOOGLE_MAPS_API_KEY', None)
            if self._key is None:
                raise KeyError
        except (AttributeError, KeyError):
            raise GoogleMapError, 'Google Maps API Key not found (set GOOGLE_MAPS_API_KEY attribute to your settings).'

        self._version = config.get('GOOGLE_MAPS_API_VERSION', '2')

        self._url = config.get('GOOGLE_MAPS_URL', GOOGLE_MAPS_URL) % (self._version, self._key)

    @property
    def onload(self):
        "Returns the `onload` function call"
        return '%s()' % self.load_func

    def retrieve_javascript(self):
        self.javascript.append(AbsLink(self._url))
        self.javascript.append(widgets.JSSource("""
addLoadEvent(function() {
    %s;
  });
var self = MochiKit.DOM;
self.addToCallStack(self._window, "onunload", %s, true);
;""" % (self.onload, self.onunload)))
        return super(GoogleMapWidget, self).retrieve_javascript()

    def retrieve_css(self):
        self.css.append(widgets.CSSSource(self.vml_css))
        return super(GoogleMapWidget, self).retrieve_css()

    def update_params(self, params):
        super(GoogleMapWidget, self).update_params(params)
        for i in ['dom_id', 'load_func', 'center_lat', 'center_lng', 'zoom']:
            params[i] = getattr(self, i)

class GeoLocationField(widgets.HiddenField, GoogleMapWidget):
    """Geo Location Widget"""

    template = 'tgsampleapp.templates.geolocation'

    readonly = False

    javascript = [widgets.mochikit,]

    message = _('Click to select geolocation')

    validator=validators.GeoLocation()

    hidden=False

    @property
    def onload(self):
        "Returns the `onload` function call"
        return '%s(); initialize();' % self.load_func

    def update_params(self, params):
        super(GeoLocationField, self).update_params(params)
        params['readonly'] = str(self.readonly).lower()
        params['message'] = self.message
        try:
            value = self.validator._to_python(params['value'], None)
        except turbogears.validators.Invalid:
            value = None
        params['python_value'] = jsonify.encode(value)


class EventForm(widgets.TableForm):
    """Event Form"""

    fields=[widgets.TextField(name="title",label=_("Title"),validator=turbogears.validators.String(not_empty=True)),
            widgets.TextField(name="description",label=_("Description"),validator=turbogears.validators.String(not_empty=True)),
            widgets.TextField(name="country",
                              label=_("Country"),
                              validator=turbogears.validators.String(not_empty=True)
                                      ),
            widgets.TextField(name="city",
                                      label=_("City"),
                              validator=turbogears.validators.String(not_empty=True)
                                      ),
            widgets.TextField(name="street",
                                      label=_("Street"),
                              validator=turbogears.validators.String(not_empty=True)
                                      ),
            widgets.TextField(name="place",
                                      label=_("Place"),
                              validator=turbogears.validators.String(not_empty=True)
                                      ),
            widgets.CalendarDateTimePicker('start_date', label=_('Start Date'), format='%Y-%m-%d'),
            widgets.CalendarDateTimePicker('end_date', label=_('End Date'), format='%Y-%m-%d'),
            GeoLocationField(name="geolocation",label=_("Geolocation")),
            ]

event_add_form = EventForm(
    action="save_created"
)

event_edit_form = EventForm(
    action="save_updated"
)

ro_template = """
    <span xmlns:py="http://purl.org/kid/ns#"
        name="${name}"
        class="${field_class}"
        id="${field_id}"
        py:content="value"
        py:attrs="attrs"
    >
    </span>
    """

class EventDisplayForm(EventForm):
    """Event Form"""

    template = """
        <table xmlns:py="http://purl.org/kid/ns#" border="0" cellspacing="0" cellpadding="2" py:attrs="table_attrs">
            <tr py:for="i, field in enumerate(fields)"
                class="${i%2 and 'odd' or 'even'}"
            >
                <th>
                    <label class="fieldlabel" for="${field.field_id}" py:content="field.label" />
                </th>
                <td>
                    <span py:replace="field.display(value_for(field), **params_for(field))" />
                    <span py:if="error_for(field)" class="fielderror" py:content="error_for(field)" />
                    <span py:if="field.help_text" class="fieldhelp" py:content="field.help_text" />
                </td>
            </tr>
        </table>
    """

    fields=[widgets.TextField(name="title",label=_("Title"), template=ro_template),
            widgets.TextField(name="description",label=_("Description"), template=ro_template),
            widgets.TextField(name="country",
                                      label=_("Country"),
                                      template=ro_template),
            widgets.TextField(name="city",
                                      label=_("City"),
                                      template=ro_template),
            widgets.TextField(name="street",
                                      label=_("Street"),
                                      template=ro_template),
            widgets.TextField(name="place",
                                      label=_("Place"),
                                      template=ro_template),
            widgets.CalendarDateTimePicker(name='start_date',
                                           label=_('Start Date'),
                                           format='%Y-%m-%d',
                                           template=ro_template),
            widgets.CalendarDateTimePicker(name='end_date',
                                           label=_('End Date'),
                                           format='%Y-%m-%d',
                                           template=ro_template),
            GeoLocationField(name="geolocation",
                             label=_("Geolocation"),
                             readonly=True)
            ]

event_display_form = EventDisplayForm(action=None)

class EventShortDisplayForm(EventDisplayForm):
    """Event Form"""

    fields=EventDisplayForm.fields[:-1]


event_short_display_form = EventShortDisplayForm()

event_map_form = GoogleMapWidget(name="geolocation",
                             label=_("Geolocation"),
                             readonly=True,
                             kml_url="/list_kml")

